package com.zjun;

import com.zjun.errorCode.BaseErrorCode;
import com.zjun.exception.AbstractException;
import com.zjun.result.Result;

import java.util.Optional;

/**
 * 全局返回对象构造器
 */
public class Results {
    /**
     * 构造响应成功
     */
    public static Result<Void> success(){
        return new Result<Void>()
                .setCode(Result.SUCCESS_CODE);
    }
    /**
     * 构造带返回数据的成功响应
     */
    public static <T> Result<T> success(T data){
        return new Result<T>()
                .setCode(Result.SUCCESS_CODE).setData(data);
    }
    /**
     * 服务端响应失败
     */
    public static Result<Void> failure(){
        return new Result<Void>()
                .setCode(BaseErrorCode.SERVICE_ERROR.errorCode());
    }

    /**
     * 带异常的失败相应
     * @param abstractException
     * @return
     */
    public static Result<Void> failuer(AbstractException abstractException){
        String errorCode = Optional.ofNullable(abstractException.getErrorCode()).orElse(BaseErrorCode.SERVICE_ERROR.errorCode());
        String errorMessage =Optional.ofNullable(abstractException.getErrorMessage()).orElse(BaseErrorCode.SERVICE_ERROR.message());
        return new Result<Void>()
                .setCode(errorCode)
                .setMessage(errorMessage);
    }

    /**
     * 自带errorCode和errorMessage构建失败响应
     */
    public static Result<Void> failure(String errorCode,String errorMessage){
        return new Result<Void>()
                .setCode(errorCode)
                .setMessage(errorMessage);
    }
}
